const http = require("http");
const fs = require("fs");
const { URL } = require("url");
const path = require("path");
const { query } = require("./db")
http.createServer((req, res) => {
    let urlObj = new URL(req.url, "http://192.168.174.166:8081/")
    let routes = {
        "GET": [
            { pathname: "/", callback: firstpage },
            { pathname: "/getChapterList", callback: listpage },
            { pathname: "/detail", callback: detailpage }
        ]
    }
    let route = routes[req.method].filter(item => item.pathname == urlObj.pathname);
    if (route[0]) {
        route[0].callback(req, res);
    }
    else if (urlObj.pathname.indexOf(".jpg") >= 0) {
        sendImage(req, res);
    }
    else {
        res.end()
    }
}).listen(8081);

//显示首页
function firstpage(req, res) {
    let filePath = path.join(__dirname, "chapterList.html")
    let fileContent = fs.readFileSync(filePath);
    res.writeHead(200, { "Content-type": "text/html;charset=utf8" });
    res.end(fileContent);
}

//显示详情页
function detailpage(req, res) {
    let filePath = path.join(__dirname, "chapter.html")
    let fileContent = fs.readFileSync(filePath);
    res.writeHead(200, { "Content-type": "text/html;charset=utf8" });
    res.end(fileContent);
}

async function listpage(req, res) {
    let sql = "select * from article";
    let results = await query(sql, []);
    console.log(results)
    res.end(JSON.stringify(results));
}

function sendImage(req, res) {
    let filePath = path.join(__dirname, req.url);
    let fileContent = fs.readFileSync(filePath);
    res.writeHead(200, { "Content-Type": "image/png" });
    res.end(fileContent);
}
console.log("server is listening 8081");